package jnpf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.model.themeLog.EntityQuery;
import jnpf.model.page.MyPageListVO;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.template.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.*;

import java.io.IOException;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;

/**
 * template
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-04-10
 */
@Slf4j
@RestController
@Tag(name = "template" , description = "example")
@RequestMapping("/api/example/Template")
public class TemplateController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private TemplateCategoryService templateCategoryService;
    @Autowired
    private TemplateAttributeService templateAttributeService;



    /**
    * 列表
    *
    * @param templatePagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody TemplatePagination templatePagination)throws IOException{
        List<TemplateEntity> list= templateService.getList(templatePagination)
                .stream()
                .filter(t -> "1".equals(t.getIsMain()))
                .collect(Collectors.toList());
        List<Map<String, Object>> realList=new ArrayList<>();

        for (TemplateEntity entity : list) {
        Map<String, Object> templateMap=JsonUtil.entityToMap(entity);
        templateMap.put("id", templateMap.get("id"));
        templateMap.put("version", entity.getVersion());

            //副表数据
        //子表数据
//        List<TemplateCategoryEntity> templateCategoryList = templateService.getTemplateCategoryList(entity.getId(),templatePagination);
//        templateMap.put("tableField110",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(templateCategoryList)));
//        List<TemplateAttributeEntity> templateAttributeList = templateService.getTemplateAttributeList(entity.getId(),templatePagination);
//        templateMap.put("tableField107",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(templateAttributeList)));
            realList.add(templateMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, TemplateConstant.getFormData(), TemplateConstant.getColumnData(), templatePagination.getModuleId(),false);

        //返回对象
        jnpf.base.vo.PageListVO vo = new jnpf.base.vo.PageListVO();
        vo.setList(realList);
        jnpf.base.vo.PaginationVO page = JsonUtil.getJsonToBean(templatePagination, jnpf.base.vo.PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }
    /**
    * 创建
    *
    * @param templateForm
    * @return
    */
    @PostMapping("/create")
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid TemplateEntity templateForm) {
        String b = templateService.checkForm(templateForm,0);
        if (StringUtil.isNotEmpty(b)){
            return ActionResult.fail(b);
        }
        try{
            boolean isSave = StringUtil.isEmpty(templateForm.getId()) ;
            templateService.saveOrUpdate(templateForm, null ,isSave);
        }catch(Exception e){
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }

    /**
     * 获取模板创建实体数量
     *
     * @param templateId
     * @return
     */
    @PostMapping("/queryEntityCount/{templateId}")
    @Operation(summary = "获取模板下实体数量")
    public ActionResult getEntityCount(@PathVariable("templateId") @NotEmpty(message = "模板id不能为空") String templateId) {
        return templateService.getEntityCount(templateId);
    }
    // 查询模板实体列表
    @PostMapping("/queryEntityList/{templateId}")
    @Operation(summary = "获取模板下实体列表")
    public ActionResult queryEntityList(@PathVariable("templateId")  @NotEmpty(message = "模板id不能为空")  String templateId,
                                        @RequestBody EntityQuery pagination) {
        MyPageListVO<EntityEntity> templateEntityList = templateService.getTemplateEntityList(templateId, pagination);
        return ActionResult.success(templateEntityList);
    }


    /**
    * 批量删除
    * @param ids
    * @return
    */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids){
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i =0;
        for (String allId : idList){
            this.delete(allId);
            i++;
        }
        if (i == 0 ){
        return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 编辑
    * @param id
    * @param templateForm
    * @return
    */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid TemplateEntity templateForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        templateForm.setId(id);
        if (!isImport) {
            String b =  templateService.checkForm(templateForm,1);
            if (StringUtil.isNotEmpty(b)){
                return ActionResult.fail(b );
            }
        }
        TemplateEntity entity= templateService.getInfo(id);
        if(entity!=null){
            try{
                templateService.saveOrUpdate(templateForm,id,false);

            }catch(Exception e){
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }


    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id){
        TemplateEntity entity= templateService.getInfo(id);
        if(entity!=null){
            //主表数据删除
            templateService.delete(entity);
            QueryWrapper<TemplateCategoryEntity> queryWrapperTemplateCategory=new QueryWrapper<>();
            queryWrapperTemplateCategory.lambda().eq(TemplateCategoryEntity::getTemplateId,entity.getId());
            //子表数据删除
            templateCategoryService.remove(queryWrapperTemplateCategory);
            QueryWrapper<TemplateAttributeEntity> queryWrapperTemplateAttribute=new QueryWrapper<>();
            queryWrapperTemplateAttribute.lambda().eq(TemplateAttributeEntity::getTemplateId,entity.getId());
            //子表数据删除
            templateAttributeService.remove(queryWrapperTemplateAttribute);
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        // 获取顶层TemplateEntity
        TemplateEntity template = templateService.getInfo(id);
        if(template == null){
            return ActionResult.fail("表单数据不存在！");
        }

        // 获取一级关联分类列表(1对多)
        List<TemplateCategoryEntity> categories = templateService.getTemplateCategoryList(template.getId());

        // 获取所有属性数据
        List<TemplateAttributeEntity> allAttributes = templateService.getTemplateAttributeList(template.getId());

        // 为每个分类设置对应的属性
        categories.forEach(category -> {
            List<TemplateAttributeEntity> attributes = allAttributes.stream()
                    .filter(attr -> category.getId().equals(attr.getCategoryId()))
                    .collect(Collectors.toList());
            category.setTemplateCategoryEntityArrayList(attributes);
        });

        // 设置分类列表到模板对象
        template.setTemplateCategoryEntityArrayList(categories);




        return ActionResult.success(template);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") @NotEmpty(message = "未传入查询id") String id){
        // 获取顶层TemplateEntity
        TemplateEntity template = templateService.getInfo(id);
        if(template == null){
            return ActionResult.fail("表单数据不存在！");
        }

        // 获取一级关联分类列表(1对多)
        List<TemplateCategoryEntity> categories = templateService.getTemplateCategoryList(template.getId());

        // 获取所有属性数据
        List<TemplateAttributeEntity> allAttributes = templateService.getTemplateAttributeList(template.getId());

        // 为每个分类设置对应的属性
        categories.forEach(category -> {
            List<TemplateAttributeEntity> attributes = allAttributes.stream()
                .filter(attr -> category.getId().equals(attr.getCategoryId()))
                .collect(Collectors.toList());
            category.setTemplateCategoryEntityArrayList(attributes);
        });

        // 设置分类列表到模板对象
        template.setTemplateCategoryEntityArrayList(categories);



        return ActionResult.success(template);
    }

}
